//
//  BKMyOrderApplyToReturnGoodsControllerViewController.m
//  bestkeep
//
//  Created by Mr. Wu on 16/12/20.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKMyOrderApplyToReturnGoodsControllerViewController.h"
#import "BK_OD_Tool.h"
#import "BKMyOrderBackGoodsCell.h"
#import "BKMyorderApplyReturnGoodsCell.h"
#import "BKMyOrderApplyReturnGoodsFooterCell.h"
#import <IQKeyboardManager.h>
#define IOS8 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 ? YES : NO)
@interface BKMyOrderApplyToReturnGoodsControllerViewController ()
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy)   NSString *returnType;
@property (nonatomic, assign) NSInteger flag;
@property (nonatomic, strong) NSMutableArray *imgURLArr;
@property (nonatomic, strong) NSMutableArray *imgArr;
@property (nonatomic, assign) int i;
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UIButton *changeButton;
@property (nonatomic, copy)   NSString *stringTextView;

@end

@implementation BKMyOrderApplyToReturnGoodsControllerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _i = 1;
    _stringTextView = @"";
    self.view.backgroundColor = RGB(242, 242, 242);
    self.title = @"申请退换货";
    _imgArr = [[NSMutableArray alloc]init];
    _imgURLArr = [[NSMutableArray alloc]init];
    _backButton = [UIButton new];
    _changeButton = [UIButton new];
    _label = [[UILabel alloc]init];
    [self initView];
    self.edgesForExtendedLayout = UIRectEdgeNone;

    
}
-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.enableAutoToolbar = NO;
    
}
-(void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    
}

- (void)initView
{
    UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"确认提交" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn.titleLabel setFont:[UIFont boldSystemFontOfSize:16.0]];
    [btn setBackgroundColor:RGB(27, 188, 155)];
    btn.layer.cornerRadius = 4;
    btn.layer.masksToBounds = YES;
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    [btn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-12);
        make.bottom.equalTo(self.view.mas_bottom).offset(-10);
        make.left.mas_equalTo(self.view.mas_left).offset(12);
        make.height.mas_equalTo(@(44));
        
    }];
    
    _tableView  = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.allowsSelection = NO;
 
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.view.mas_right).offset(0);
        make.bottom.mas_equalTo(btn.mas_top).offset(-10);
        make.left.mas_equalTo(self.view.mas_left).offset(0);
        make.top.mas_equalTo(self.view.mas_top).offset(0);
        
    }];
   }

#pragma mark - tableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else{
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
       BKMyOrderBackGoodsCell* cell = [_tableView dequeueReusableCellWithIdentifier:@"cell"] ;
        if (cell == nil) {
            cell = [[BKMyOrderBackGoodsCell alloc]init];
      
        cell.ordermodel = self.OrderModel;
        [cell.backButton removeFromSuperview];
              }
        return cell;
    }else if(indexPath.section == 1){
        BKMyorderApplyReturnGoodsCell* cell = [_tableView dequeueReusableCellWithIdentifier:@"detail"];
        if (cell == nil) {
            cell = [[BKMyorderApplyReturnGoodsCell alloc] init];
            [cell.lostBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
            [cell.changeBtn addTarget:self action:@selector(changeAction:) forControlEvents:UIControlEventTouchUpInside];
            _backButton = cell.lostBtn;
            _changeButton = cell.changeBtn;
            [cell.reduceBtn addTarget:self action:@selector(reduceAction:) forControlEvents:UIControlEventTouchUpInside];
            [cell.addBtn addTarget:self action:@selector(addDataAction:) forControlEvents:UIControlEventTouchUpInside];
            _label = cell.goodsDataLabel;
            cell.ordermodel = self.OrderModel;
            return cell;
        }
    }else if (indexPath.section == 2){
       BKMyOrderApplyReturnGoodsFooterCell* cell = [_tableView dequeueReusableCellWithIdentifier:@"footer"];
        if (cell == nil) {
            cell = [[BKMyOrderApplyReturnGoodsFooterCell alloc] init];
            cell.applyAddImage.tag = 200;
            cell.applyAddImage1.tag = 201;
            cell.applyAddImage2.tag = 202;
            cell.delegate= self;
            [cell.applyAddImage addTarget:self action:@selector(uploadPicture:) forControlEvents:UIControlEventTouchUpInside];
            [cell.applyAddImage1 addTarget:self action:@selector(uploadPicture:) forControlEvents:UIControlEventTouchUpInside];
            [cell.applyAddImage2 addTarget:self action:@selector(uploadPicture:) forControlEvents:UIControlEventTouchUpInside];
            return cell;
        }
    }
    
    return nil;
}

#pragma mark - TableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 116;//110->116
    }else if (indexPath.section == 1){
        return 176;//170->176
    }else if (indexPath.section == 2){
        return 250;//250->258
    }else{
        return 44;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}

-(void)reduceAction:(UIButton *)button{
    if (_i<=1) {
        [HUD showMessage:@"申请数量不能小于1"];
       
        button.userInteractionEnabled=NO;
      
        
    }else{
        _i--;
        _label.text = [NSString stringWithFormat:@"%d",_i];
    }
}

-(void)addDataAction:(UIButton *)button{
    int totalAmount = 0;
    int value;
    value = [self.OrderModel.amount intValue];
    totalAmount = totalAmount+value;
    if ([_label.text intValue] >= totalAmount) {
         [HUD showMessage:@"申请数量不能大于所购数量"];
    }else{
        _i++;
        _label.text = [NSString stringWithFormat:@"%d",_i];
    }
    
}

-(void)backAction:(UIButton *)button{
    button.selected = !button.selected;
    _changeButton.layer.borderColor = [UIColor grayColor].CGColor;
    _backButton.layer.borderColor = RGB(27, 188, 155).CGColor;
    [_backButton setTitleColor:RGB(27, 188, 155) forState:UIControlStateNormal];
    [_changeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _returnType = @"1";
}

-(void)changeAction:(UIButton *)button{
    button.selected = !button.selected;
    _backButton.layer.borderColor = [UIColor grayColor].CGColor;
    _changeButton.layer.borderColor = RGB(27, 188, 155).CGColor;
    [_backButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_changeButton setTitleColor:RGB(27, 188, 155) forState:UIControlStateNormal];
    
    _returnType = @"2";
}

-(void)uploadPicture:(UIButton *)button{
    _flag = button.tag;
    if (IOS8) {
        UIAlertController*alterController =[UIAlertController alertControllerWithTitle:@"获取图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIAlertAction *defaultaction =[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                UIImagePickerController *imagePickerController =[[UIImagePickerController alloc]init];
                imagePickerController.delegate = self;
                imagePickerController.allowsEditing = YES;
                imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:imagePickerController animated:YES completion:^{
                    
                }];
                
            }];
            [alterController addAction:defaultaction];
        }
        
        UIAlertAction *defaultAction1 =[UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIImagePickerController *imagePickerController =[[UIImagePickerController alloc]init];
            imagePickerController.delegate =self;
            imagePickerController.allowsEditing = YES;
            imagePickerController.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:imagePickerController animated:YES completion:^{
                
            }];
        }];
        UIAlertAction *cancelAction =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alterController addAction:cancelAction];
        [alterController addAction:defaultAction1];
        [self presentViewController:alterController animated:YES completion:nil];
    }else{
        UIActionSheet *sheet;
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            sheet = [[UIActionSheet alloc] initWithTitle:@"获取图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选择",@"拍照", nil];
        }
        else{
            sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选择",nil];
        }
        [sheet showInView:self.view];
    }
}
#pragma mark  判断是否支持拍照功能调用
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSUInteger sourceType = 0;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        switch ((NSInteger)buttonIndex){
            case 0:
                // 相册
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                break;
            case 1:
                // 相机
                sourceType = UIImagePickerControllerSourceTypeCamera;
                break;
            case 2:
                
                return;
                
        }
    }
    else{
        if (buttonIndex == 0){
            sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        }
        else{
            
            return;
        }
    }
    // 跳转到相机或相册页面
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
    [self presentViewController:imagePickerController animated:YES completion:^{
        
    }];//跳转到相册
    
}
#pragma mark - image picker delegte
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    NSData *imageData = nil;
    if ([mediaType isEqualToString:@"public.image"]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];//获得用户编辑后的图片
        [self setImage: image];
        [_imgArr addObject:image];
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera){
            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);//保存到相机胶卷目录
        }
    }
    
    [[NSUserDefaults standardUserDefaults] setObject:imageData forKey:@"userImage"];
    [picker dismissViewControllerAnimated:YES completion:^{
        UIButton *but = (UIButton *)[self.tableView viewWithTag:_flag+1];
        but.hidden = NO;
        
    }];
    
    
    
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

-(void)setImage: (UIImage *)img{
    UIButton *button = (UIButton *)[self.tableView viewWithTag:_flag];
    [button setImage:img forState:UIControlStateNormal];
    
}

#pragma mark -拍照后保存图片回调方法
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    
}


- (void)btnClick:(UIButton*)sender //确认提交
{
    if (_imgArr.count==0) {
         [HUD showMessage:@"请上传图片"];
        
    }else if (!([_returnType isEqualToString:@"1"]||[_returnType isEqualToString:@"2"])){
        [HUD showMessage:@"请选择退货或换货"];

    }else if ([_stringTextView isEqualToString:@""]||[_stringTextView isEqualToString:@"请在此描述详细问题"]){
        [HUD showMessage:@"请在此描述详细问题"];
        
    } else {
        [BKIndicationView showInView:self.view];
         [_imgURLArr removeAllObjects];
        for (UIImage *image in self.imgArr) {
            CGFloat compressionQuality;
            if(image.size.height > 3000 || image.size.width > 3000) {
                compressionQuality = 0.3;
            } else if (image.size.height > 1500 || image.size.width > 1500){
                compressionQuality = 0.5;
            } else {
                compressionQuality = 0.8;
            }
            NSData *imgData = UIImageJPEGRepresentation(image, compressionQuality);
            
            [BKMyOrderGetDataFromNetWork uploadImage:imgData imageName:@"image.jpg" Success:^(id Response) {
                BOOL success = [Response[@"success"] boolValue];
                if(success == YES)
                {
                   
                    
                [_imgURLArr addObject:[Response objectForKey:@"urls"]];
                    
                    if (_imgURLArr.count == _imgArr.count) {
                        [self gotoConfrim];
                    }
               }
                else{
                    [HUD showMessage:@"上传图片失败"];
                    [BKIndicationView dismiss];
                }
            }failure:^(NSError *error) {
                [HUD showMessage:@"上传图片失败"];
                [BKIndicationView dismiss];
                return ;
            }];

        }
}
}
-(void)gotoConfrim{
    
    
    NSDictionary *dic =[NSDictionary dictionaryWithObjectsAndKeys:self.OrderModel.order_item_id,@"orderItemId",[_imgArr componentsJoinedByString:@","],@"goodsImgs",_stringTextView,@"returnreason",_returnType,@"returntype", nil];
    [BKMyOrderGetDataFromNetWork OrderReturnGoodsDic:dic Status:^(NSString *str) {
        if ([str isEqualToString:@"1"]) {
            [HUD showSuccessMessage:@"退换货成功"];
            [BKIndicationView dismiss];
           [self.navigationController popToRootViewControllerAnimated:YES];
            
        }else{
            
            [HUD showMessage:str];
            [BKIndicationView dismiss];
        }
    }];
    
    
    }
-(void)getTextFieldString:(NSString *)text
{
    _stringTextView = text;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
